import os
import configparser

class ConfigManager:
    """配置管理器"""
    _instance = None
    
    def __new__(cls):
        """单例模式"""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        """初始化配置管理器"""
        if not hasattr(self, 'config'):
            self.config = configparser.ConfigParser()
            self.config_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                'config',
                'config.ini'
            )
            self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        try:
            self.config.read(self.config_path, encoding='utf-8')
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            # 使用默认配置
            self.config['main'] = {
                'title': '我的应用'
            }
    
    def get(self, section, key, default=None):
        """获取配置值"""
        try:
            return self.config.get(section, key)
        except:
            return default
    
    def set(self, section, key, value):
        """设置配置值"""
        if not self.config.has_section(section):
            self.config.add_section(section)
        self.config.set(section, key, value)
        self.save()
    
    def save(self):
        """保存配置到文件"""
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                self.config.write(f)
        except Exception as e:
            print(f"保存配置文件失败: {e}") 